package com.hopu.util;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传
 */
public class FileUtil {
    public static String upload(MultipartFile fileStream ) throws  Exception{
        String thisProjectPath = null;
        try {
            String originalFilename = fileStream.getOriginalFilename();
            //文件后缀
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 获取项目根路径
            thisProjectPath = System.getProperty("user.dir");
            thisProjectPath = URLDecoder.decode(thisProjectPath, "UTF-8");

            String newFileName = UUID.randomUUID().toString().replace("-", "");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String folder = format.format(new Date());

            String path =thisProjectPath+ File.separator+"src"+File.separator+"main"+File.separator+"webapp"+File.separator+"upload"
                    +File.separator+folder+File.separator+newFileName+fileSuffix;
            File file = new File(path);
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdir();
            }
            try {
                FileUtils.copyInputStreamToFile(fileStream.getInputStream(),file);
                // 上传成功
                return  "/upload/"+folder+"/"+newFileName+fileSuffix;

            } catch (IOException e) {
                e.printStackTrace();
                // 上传失败
                return  null;
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
